from strategy.base import Strategy
from loguru import logger

# 债券目标仓位策略类
class BondTargetPositionStrategy(Strategy):
    """债券目标仓位策略"""
    
    def __init__(self, name, target_positions, start_date, end_date,portfolio_flag=True):
        """
        初始化策略
        
        Args:
            name: 策略名称
            target_positions: 目标仓位 {date: {symbol: weight}}
            start_date: 回测开始日期
            end_date: 回测结束日期
        """
        super().__init__(name, portfolio_flag)
        self.target_positions = target_positions
        self.start_date = start_date
        self.end_date = end_date
        self.market_data_initialized = False
        # self.portfolio_flag = portfolio_flag
        
    def set_engine(self, engine):
        """设置回测引擎"""
        super().set_engine(engine)
        # 确保市场数据正确初始化
        logger.info(f"市场数据键值: {list(self.market_data.keys())}")
        self.market_data_initialized = True
        
    def initialize(self):
        """策略初始化"""
        logger.info("策略初始化完成")
        
    def on_dataset(self, data):
        """每个交易日执行"""
        # 确保市场数据已经初始化
        if not self.market_data_initialized:
            logger.error("市场数据未初始化")
            return
            
        current_date = self.engine.current_time
        self.current_date = self.engine.current_time  # 确保当前日期设置正确
        
        logger.info(f"当前日期: {current_date}")
        # 检查是否有当天的目标仓位
        if current_date in self.target_positions.keys():
            logger.info(f"发现目标仓位: {self.target_positions[current_date]}")
            target_weights = self.target_positions[current_date]
            symbol2pop = []
            try:
                # 确保能获取市场价格
                for symbol in target_weights:
                    if symbol not in self.market_data:
                        logger.info(f"市场数据中找不到{symbol}，可用的市场数据: {list(self.market_data.keys())}")
                        symbol2pop.append(symbol)
                    
                # 调整目标仓位
                if symbol2pop:
                    for symbol_ in symbol2pop:
                        logger.info(f"剔除没有行情的持仓: {symbol_}")
                        target_weights.pop(symbol_) #剔除没有行情的持仓
                        logger.info(f"剔除后的目标仓位: {target_weights}")
                if target_weights:
                    self.adjust_target_position(target_weights)
                    logger.info(f"目标仓位调整完成: {target_weights}")
            except Exception as e:
                logger.error(f"调整目标仓位时出错: {str(e)}")
        else:
            pass
            # logger.info(f"今日无需调仓")
            
    def on_order_fill(self, trade):
        """订单成交回调"""
        pass